package cn.dckeji.gameBox.common.utils;

import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.setting.dialect.Props;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Lucas
 * @date 2018/3/29
 * @package cn.dckeji.gameBox.common.utils
 * @Description
 */
public class WxUtil {

    private static final Logger LOGGER = Logger.getLogger(WxUtil.class);

    /**
     * 获取请求用户信息的access_token
     *
     * @param code
     * @return
     */
    public static Map<String, String> getUserInfoAccessToken(String code) {

        //加载微信配置文件
        Props props = new Props("wx.properties", "utf-8");
        String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                props.getStr("WX_APPID"), props.getStr("WX_APPSECRET"), code);
        JsonObject object = null;

        Map<String, String> data = new HashMap();
        try {

            LOGGER.info("获取请求用户信息的access_token的微信url: {" + url + "}");
            String tokens = HttpUtil.get(url);
            LOGGER.info("获取请求用户信息的access_token的微信返回信息: {" + tokens + "}");
            Gson token_gson = new Gson();
            object = token_gson.fromJson(tokens, JsonObject.class);
            LOGGER.info("request accessToken success. [result={" + object + "}]");

            data.put("openid", object.get("openid").toString().replaceAll("\"", ""));
            data.put("access_token", object.get("access_token").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            LOGGER.error("fail to request wechat access token. [error={" + ex + "}]");
        }
        return data;
    }


    /**
     * 获取用户信息
     *
     * @param accessToken
     * @param openId
     * @return
     */
    public static Map<String, String> getUserInfo(String accessToken, String openId) {

        Map<String, String> data = new HashMap();
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        LOGGER.info("request user info from url: {" + url + "}");
        JsonObject userInfo = null;
        try {
            LOGGER.info("获取用户信息的微信url: {" + url + "}");
            String s = HttpUtil.get(url);
            LOGGER.info("获取用户信息的微信返回信息: {" + s + "}");

            Gson token_gson = new Gson();
            userInfo = token_gson.fromJson(s, JsonObject.class);
            LOGGER.info("get userinfo success. [result={" + userInfo + "}]");

            data.put("openid", userInfo.get("openid").toString().replaceAll("\"", ""));
            data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", ""));
            data.put("city", userInfo.get("city").toString().replaceAll("\"", ""));
            data.put("province", userInfo.get("province").toString().replaceAll("\"", ""));
            data.put("country", userInfo.get("country").toString().replaceAll("\"", ""));
            data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", ""));
        } catch (Exception ex) {
            LOGGER.error("fail to request wechat user info. [error={" + ex + "}]");
        }
        return data;
    }


    /**
     * 去掉nick种的emoji
     *
     * @param nickname
     * @return
     */
    public static String subStringEmoji(String nickname) {
        //去掉emoji
        String pattern="(?:[\uD83C\uDF00-\uD83D\uDDFF]|[\uD83E\uDD00-\uD83E\uDDFF]|[\uD83D\uDE00-\uD83D\uDE4F]|[\uD83D\uDE80-\uD83D\uDEFF]|[\u2600-\u26FF]\uFE0F?|[\u2700-\u27BF]\uFE0F?|\u24C2\uFE0F?|[\uD83C\uDDE6-\uD83C\uDDFF]{1,2}|[\uD83C\uDD70\uD83C\uDD71\uD83C\uDD7E\uD83C\uDD7F\uD83C\uDD8E\uD83C\uDD91-\uD83C\uDD9A]\uFE0F?|[\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3|[\u2194-\u2199\u21A9-\u21AA]\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?|[\u2934\u2935]\uFE0F?|[\u3030\u303D]\uFE0F?|[\u3297\u3299]\uFE0F?|[\uD83C\uDE01\uD83C\uDE02\uD83C\uDE1A\uD83C\uDE2F\uD83C\uDE32-\uD83C\uDE3A\uD83C\uDE50\uD83C\uDE51]\uFE0F?|[\u203C\u2049]\uFE0F?|[\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE]\uFE0F?|[\u00A9\u00AE]\uFE0F?|[\u2122\u2139]\uFE0F?|\uD83C\uDC04\uFE0F?|\uD83C\uDCCF\uFE0F?|[\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA]\uFE0F?)";
        String reStr = "特殊字符";
        Pattern emoji = Pattern.compile(pattern);
        Matcher emojiMatcher = emoji.matcher(nickname);
        return emojiMatcher.replaceAll(reStr);
    }


    /**
     * 获access_token
     * @return
     */
    public static Map<String, String> getAccessToken() {
        Props props = new Props("wx.properties","utf-8");
        String wx_appid = props.getStr("WX_APPID");
        String wx_appsecret = props.getStr("WX_APPSECRET");

        Map<String, String> data = new HashMap();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + wx_appid + "&secret=" + wx_appsecret;

        LOGGER.info("request user info from url: {" + url + "}");
        JsonObject accessTokenInfo = null;
        try {
            String s = HttpUtil.get(url);
            Gson token_gson = new Gson();

            accessTokenInfo = token_gson.fromJson(s, JsonObject.class);
            LOGGER.info("get accessTokenInfo success. [result={" + accessTokenInfo + "}]");

            data.put("access_token", accessTokenInfo.get("access_token").toString().replaceAll("\"", ""));
            data.put("expires_in", accessTokenInfo.get("expires_in").toString().replaceAll("\"", ""));

        } catch (Exception ex) {
            LOGGER.error("fail to request wechat user info. [error={" + ex + "}]");
        }
        return data;
    }



    /**
     * 判断用户是否关注了公众号
     * @param token
     * @param openid
     * @return
     */
    public static boolean judgeIsFollow(String token,String openid){
        String subscribe="0";
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openid+"&lang=zh_CN";
        JsonObject jude = null;

        try {
            String s = HttpUtil.get(url);
            Gson token_gson = new Gson();

            jude = token_gson.fromJson(s, JsonObject.class);
            subscribe = jude.get("subscribe").toString().replaceAll("\"", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "1".equals(subscribe)?true:false;
    }
}
